import configparser
import json
import os
import datetime
import requests
from httpsig.requests_auth import HTTPSignatureAuth

# 获取配置文件
dir_name = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
ini_path = f"{dir_name}/zabbix_sync_script/config.ini"

config = configparser.RawConfigParser()
config.read(ini_path)


# 获取认证信息 APIKey
def get_auth(KeyID, SecretID):
    signature_headers = ['(request-target)', 'accept', 'date']
    auth = HTTPSignatureAuth(key_id=KeyID, secret=SecretID, algorithm='hmac-sha256', headers=signature_headers)
    return auth


# 查询节点信息
def get_node_info(jms_url, jms_auth, headers, node_name):
    """
    查询节点信息
    :param jms_url: str
    :param jms_auth: str
    :param node_name: str
    :param headers: dict
    :return:
    """
    url = f"{jms_url}/api/v1/assets/nodes/"
    response = requests.get(url, auth=jms_auth, headers=headers, params={
        "value": node_name
    })
    node_info = json.loads(response.text)
    return node_info


# 创建 node节点
def create_node(jms_url, jms_auth, headers, node_name):
    """
    创建node节点
    :param jms_url: str
    :param jms_auth: str
    :param node_name: str
    :param headers: dict
    :return:
    """
    data = {"value": node_name}
    url = f"{jms_url}/api/v1/assets/nodes/"
    resp = requests.post(url, headers=headers, auth=jms_auth, data=json.dumps(data))
    node_data = json.loads(resp.text)
    return node_data


def create_children_node(jms_url, jms_auth, headers, parents_node_id, node_name):
    """
    创建子node节点
    :param jms_url: str
    :param jms_auth: str
    :param parents_node_id: str
    :param node_name: str
    :param headers: dict
    :return:
    """
    url = f"{jms_url}/api/v1/assets/nodes/{parents_node_id}/children/"
    data = {"value": node_name}
    resp = requests.post(url, headers=headers, auth=jms_auth, data=json.dumps(data))
    node_data = json.loads(resp.text)
    return node_data


def get_children_node(jms_url, jms_auth, headers, parents_node_id, node_name):
    """
    获取某个node节点下的子节点信息
    :param jms_url: str
    :param jms_auth: str
    :param parents_node_id:
    :param headers: dict
    :param node_name:
    :return:
    """
    url = f"{jms_url}/api/v1/assets/nodes/{parents_node_id}/children/"
    response = requests.get(url, headers=headers, auth=jms_auth)
    return response.json()


# 通过IP查找资产
def get_assets_list_by_ip(jms_url, jms_auth, headers, ip):
    """
    通过IP查找资产
    :param jms_url: str
    :param jms_auth: str
    :param headers: dict
    :param ip: str
    :return:
    """
    url = f"{jms_url}/api/v1/assets/assets/"
    assets_list_info = requests.get(url, headers=headers, auth=jms_auth, params={
        "ip": ip,
    })
    assets_list = json.loads(assets_list_info.text)
    return assets_list


def get_assets(jms_url, jms_auth, headers, search_type, value):
    """
    自定义 查找资产
    :param jms_url: str
    :param jms_auth: str
    :param search_type: str
    :param headers: dict
    :param value: str
    :return:
    """
    url = f"{jms_url}/api/v1/assets/assets/"
    assets_list_info = requests.get(url, headers=headers, auth=jms_auth, params={
        search_type: value
    })
    assets_list = json.loads(assets_list_info.text)
    return assets_list


# 创建资产
def create_asset(jms_url, jms_auth, headers, ip, hostname, platform, protocol, port, node_id_list, comment, cpu_cores,
                 memory,
                 disk_total, sn, vendor, number, device_model):
    """
    创建资产
    :param jms_url: str jumpserver URL
    :param jms_auth: str jumpserver token
    :param headers: dict
    :param platform: 平台
        Linux / Unix / MacOS / BSD / Windows / Windows2016 / Other / Windows-RDP / Windows-TLS / AIX
    :param protocol: str 协议
    :param port: str 端口
    :param ip: str ip地址
    :param hostname: str 设备名称
    :param node_id_list: list 节点id列表
    :param comment: str 备注
    :param cpu_cores: int cpu核数
    :param memory: str 内存
    :param disk_total: str 硬盘
    :param sn: str 序列号
    :param vendor: str 厂商
    :param number: str 资产编号
    :param device_model: str 设备型号

    :return:
    """
    data = {
        "hostname": hostname,
        "ip": ip,
        "platform": platform,
        "protocol": protocol,
        "port": port,
        "is_active": True,
        "comment": comment,
        "nodes": node_id_list,
        "cpu_cores": cpu_cores,
        "memory": memory,
        "disk_total": disk_total,
        "sn": sn,
        "vendor": vendor,
        "number": number,
        "model": device_model,
    }
    url = f"{jms_url}/api/v1/assets/assets/"
    resp = requests.post(url=url, headers=headers, auth=jms_auth, data=json.dumps(data))
    create_resp = json.loads(resp.text)
    return create_resp


def update_asset(jms_url, jms_auth, headers, jumpserver_id, update_data):
    """
    获取所有系统用户
    :param jms_url: str
    :param jms_auth: str
    :param headers: dict
    :param jumpserver_id: str
    :param update_data: dict
    :return:
    """
    url = f"{jms_url}/api/v1/assets/assets/{jumpserver_id}/"
    resp = requests.patch(url=url, headers=headers, auth=jms_auth, data=json.dumps(update_data))
    updata_resp = json.loads(resp.text)
    return updata_resp


def get_asset_by_id(jms_url, jms_auth, headers, jumpserver_id):
    """
    通过ip获取资产信息
    :param jms_url: str
    :param jms_auth: str
    :param headers: dict
    :param jumpserver_id: str
    :return:
    """
    url = f"{jms_url}/api/v1/assets/assets/{jumpserver_id}/"
    resp = requests.get(url=url, headers=headers, auth=jms_auth)
    asset_info = json.loads(resp.text)
    return asset_info


# 获取所有用户组
def get_user_groups(jms_url, jms_auth, headers, user_groups_name):
    """
    获取用户组
    :param jms_url: str
    :param jms_auth: str
    :param headers: dict
    :param user_groups_name: str
    :return:
    """
    url = f"{jms_url}/api/v1/users/groups/"
    groups_resp = requests.get(url=url, headers=headers, auth=jms_auth, params={"name": user_groups_name})
    groups_info = json.loads(groups_resp.text)
    return groups_info


def create_user_groups(jms_url, jms_auth, headers, user_groups_name, comment, users_id_list=None):
    """
    创建用户组
    :param jms_url: str
    :param jms_auth: str
    :param headers: dict
    :param user_groups_name: str
    :param comment: str
    :param users_id_list: list
    :return:
    """
    if not users_id_list:
        users_id_list = []
    url = f"{jms_url}/api/v1/users/groups/"
    data = {
        "users": users_id_list,
        "name": user_groups_name,
        "comment": comment
    }
    groups_resp = requests.post(url=url, headers=headers, auth=jms_auth, data=json.dumps(data))
    groups_info = json.loads(groups_resp.text)
    return groups_info


def get_user(jms_url, jms_auth, headers, username):
    """
    根据用户名获取用户
    :param jms_url: str
    :param jms_auth: str
    :param headers: dict
    :param username: str
    :return:
    """
    url = f"{jms_url}/api/v1/users/users/"
    users_resp = requests.get(url=url, headers=headers, auth=jms_auth, params={"name": username})
    users_info = json.loads(users_resp.text)
    return users_info


def create_user(jms_url, jms_auth, headers, username, email, password, system_roles, groups_id_list=None):
    """
    创建用户
    :param jms_url: str
    :param jms_auth: str
    :param headers: dict
    :param username: str
    :param email: str
    :param password: str
    :param system_roles: list
        00000000-0000-0000-0000-000000000001 :系统管理员
        00000000-0000-0000-0000-000000000002 :系统审计员
        00000000-0000-0000-0000-000000000003 :用户
    :param groups_id_list: list
    :return:
    """
    if not groups_id_list:
        groups_id_list = []
    url = f"{jms_url}/api/v1/users/users/"
    data = {
        "password_strategy": "custom",
        "need_update_password": False,
        "mfa_level": 0,
        "name": username,
        "username": username,
        "email": email,
        "groups": groups_id_list,
        "password": password,
        "system_roles": system_roles
    }
    users_resp = requests.post(url=url, headers=headers, auth=jms_auth, data=json.dumps(data))
    users_info = json.loads(users_resp.text)
    return users_info


def get_perms(jms_url, jms_auth, headers, ):
    """
    查询权限数据信息
    :param jms_url: str
    :param jms_auth: str
    :param headers: dict
    :return:
    """
    url = f"{jms_url}/api/v1/perms/asset-permissions/"
    perms_resp = requests.get(url=url, headers=headers, auth=jms_auth)
    perms_info = json.loads(perms_resp.text)
    return perms_info


def create_perms(jms_url, jms_auth, headers, perms_name, usergroup_ids, node_ids, assets=None):
    """
    创建权限数据
    :param jms_url: str
    :param jms_auth: str
    :param headers: dict
    :param assets: list
    :param perms_name: str
    :param usergroup_ids: list
    :param node_ids: list
    :return:
    """
    if not assets:
        assets = []
    url = f"{jms_url}/api/v1/perms/asset-permissions/"
    data = {
        "assets": assets,
        "nodes": node_ids,
        "actions": [
            "all",
            "connect",
            "upload_file",
            "download_file",
            "updownload",
            "clipboard_copy",
            "clipboard_paste",
            "clipboard_copy_paste"
        ],
        "is_active": True,
        "name": perms_name,
        "user_groups": usergroup_ids
    }
    perms_resp = requests.post(url=url, headers=headers, auth=jms_auth, data=json.dumps(data))
    perms_info = json.loads(perms_resp.text)
    return perms_info


def get_platforms(jms_url, jms_auth, headers):
    """
    查询平台列表
    :param jms_url: str
    :param jms_auth: str
    :param headers: dict
    :return:
    """
    url = f"{jms_url}/api/v1/assets/platforms/"
    platforms_resp = requests.get(url=url, headers=headers, auth=jms_auth)
    paltforms_info = json.loads(platforms_resp.text)
    return paltforms_info


def create_platform(jms_url, jms_auth, headers, platforms_base, platform_name, comment):
    """
    创建平台
    :param jms_url: str
    :param jms_auth: str
    :param headers: dict
    :param platforms_base: str
    :param platform_name: str
    :param comment: str
    :return:
    """
    url = f"{jms_url}/api/v1/assets/platforms/"
    data = {
        "base": platforms_base,
        "charset": "utf8",
        "comment": comment,
        "name": platform_name
    }
    platform_create = requests.post(url=url, headers=headers, auth=jms_auth, data=json.dumps(data))
    platform_info = json.loads(platform_create.text)
    return platform_info


def association_systemuser(jms_url, jms_auth, headers, asset_id, systemuser_id):
    """
    资产关联 系统 普通用户
    :param jms_url: str
    :param jms_auth: str
    :param headers: dict
    :param systemuser_id: str
    :param asset_id:  str
    :return:
    """
    url = f"{jms_url}/api/v1/assets/system-users-assets-relations/"
    data = {
        "asset": asset_id,
        "systemuser": systemuser_id
    }
    association = requests.post(url=url, headers=headers, auth=jms_auth, data=json.dumps(data))
    association_info = json.loads(association.text)
    return association_info


def get_system_user(jms_url, jms_auth, headers):
    """
    获取所有系统用户
    :param jms_url: str
    :param jms_auth: str
    :param headers: dict
    :return:
    """
    url = f"{jms_url}/api/v1/assets/system-users/"
    system_user_resp = requests.get(url=url, headers=headers, auth=jms_auth)
    system_user_list = json.loads(system_user_resp.text)
    return system_user_list
